package com.lwl.blue.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lwl.blue.commont.base.*;
import com.lwl.blue.commont.utils.UserContextUtil;
import com.lwl.blue.entity.PurchaseOrder;
import com.lwl.blue.entity.PurchaseOrderDetail;
import com.lwl.blue.entity.RejectRequest;
import com.lwl.blue.service.PurchaseOrderDetailService;
import com.lwl.blue.service.PurchaseOrderService;
import com.lwl.blue.vo.LoginUserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/purchaseOrder")
public class PurchaseOrderController extends BaseController {

    @Autowired
    private PurchaseOrderService purchaseOrderService;
    @Autowired
    private PurchaseOrderDetailService purchaseOrderDetailService;

    /**
     * 分页查询采购订单。
     */
    @PostMapping("/pages")
    public PageResult<PurchaseOrder> pages(@RequestBody PageParam<PurchaseOrder> pageParam) {
        JsonResult<Page<PurchaseOrder>> pages = purchaseOrderService.pages(pageParam);
        PageResult<PurchaseOrder> re = new PageResult<>();
        re.success(pages.getData().getTotal(), pages.getData().getRecords());
        return re;
    }

    /**
     * 新增或更新采购订单（根据是否存在主键区分）。
     */
    @PostMapping("/saveOrUpdate")
    public JsonResult<String> saveOrUpdate(@RequestBody PurchaseOrder param) {
        // 处理空日期字段，将空字符串设置为当前日期
        String currentDate = java.time.LocalDate.now().toString(); // 格式：YYYY-MM-DD
        
        if (param.getSignDate() == null || param.getSignDate().trim().isEmpty()) {
            param.setSignDate(currentDate);
        }
        if (param.getValidStartDate() == null || param.getValidStartDate().trim().isEmpty()) {
            param.setValidStartDate(currentDate);
        }
        if (param.getValidEndDate() == null || param.getValidEndDate().trim().isEmpty()) {
            param.setValidEndDate(currentDate);
        }
        if (param.getExpectedDeliveryDate() == null || param.getExpectedDeliveryDate().trim().isEmpty()) {
            param.setExpectedDeliveryDate(currentDate);
        }
        if (param.getPickupPeriodStart() == null || param.getPickupPeriodStart().trim().isEmpty()) {
            param.setPickupPeriodStart(currentDate);
        }
        if (param.getPickupPeriodEnd() == null || param.getPickupPeriodEnd().trim().isEmpty()) {
            param.setPickupPeriodEnd(currentDate);
        }
        
        setInsetOrUpdateUser(param);
        // 兼容表结构中非空字段：creator_id、updater_id
        String loginUser = UserContextUtil.getUser() == null ? null : UserContextUtil.getUser().getUserName();
        // 兼容前端：编辑页传的是 purchaseOrderId，将其映射为 id，避免被当做新增
        if (param.getId() == null && param.getPurchaseOrderId() != null && !param.getPurchaseOrderId().trim().isEmpty()) {
            param.setId(param.getPurchaseOrderId());
        }
        
        // 新增订单时生成UUID主键
        if (param.getId() == null || param.getId().trim().isEmpty()) {
            param.setId(java.util.UUID.randomUUID().toString());
        }

        // order_no 唯一校验：更新时排除自身
        QueryWrapper<PurchaseOrder> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(PurchaseOrder::getOrderNo, param.getOrderNo());
        if (param.getId() != null) {
            wrapper.lambda().ne(PurchaseOrder::getId, param.getId());
        }
        int exists = purchaseOrderService.count(wrapper);
        if (exists > 0) {
            return new JsonResult<String>().error("订单号已存在：" + param.getOrderNo());
        }
        if (param.getId() == null) {
            // 新增时写入创建人
            if (param.getCreatorId() == null) {
                param.setCreatorId(loginUser);
            }
        }
        // 新增或修改都写入修改人
        param.setUpdaterId(loginUser);
        purchaseOrderService.saveOrUpdate(param);
        return new JsonResult<String>().success("请求成功", null);
    }

    /**
     * 物理删除采购订单（直接从数据库删除）。
     */
    @PostMapping("/delete/{id}")
    public JsonResult<String> delete(@PathVariable("id") String id) {
        // 先删除相关的明细数据
        QueryWrapper<PurchaseOrderDetail> detailWrapper = new QueryWrapper<>();
        detailWrapper.lambda().eq(PurchaseOrderDetail::getPurchaseOrderId, id);
        purchaseOrderDetailService.remove(detailWrapper);
        // 再删除主表数据
        purchaseOrderService.removeById(id);
        return new JsonResult<String>().success("请求成功", null);
    }

    /**
     * 批量物理删除采购订单（直接从数据库删除）。
     */
    @PostMapping("/deleteByIds")
    public JsonResult<String> deleteByIds(@RequestBody List<String> ids) {
        // 先删除相关的明细数据
        QueryWrapper<PurchaseOrderDetail> detailWrapper = new QueryWrapper<>();
        detailWrapper.lambda().in(PurchaseOrderDetail::getPurchaseOrderId, ids);
        purchaseOrderDetailService.remove(detailWrapper);
        // 再删除主表数据
        purchaseOrderService.removeByIds(ids);
        return new JsonResult<String>().success("请求成功", null);
    }

    /**
     * 根据ID查询单条采购订单。
     */
    @PostMapping("/getById/{id}")
    public JsonResult<PurchaseOrder> getById(@PathVariable("id") String id) {
//        purchaseOrderService.getById(id);
        return purchaseOrderService.getByPk(id);
    }

    /**
     * 提交订单（状态从准备变为待审）
     */
    @PostMapping("/submit/{id}")
    public JsonResult<String> submitOrder(@PathVariable("id") String id) {
        PurchaseOrder order = purchaseOrderService.getById(id);
        if (order == null) {
            return new JsonResult<String>().error("订单不存在");
        }
        
        // 检查当前状态是否为准备状态
        if (!"10".equals(String.valueOf(order.getDocStatus()))) {
            return new JsonResult<String>().error("只有准备状态的订单才能提交");
        }
        
        // 更新状态为待审
        order.setDocStatus(30);
        setInsetOrUpdateUser(order);
        purchaseOrderService.updateById(order);
        
        return new JsonResult<String>().success("订单已提交，等待审核", null);
    }

    /**
     * 生成合同（状态从执行变为完结）
     */
    @PostMapping("/generateContract/{id}")
    public JsonResult<String> generateContract(@PathVariable("id") String id) {
        PurchaseOrder order = purchaseOrderService.getById(id);
        if (order == null) {
            return new JsonResult<String>().error("订单不存在");
        }
        
        // 检查当前状态是否为执行状态
        if (!"70".equals(String.valueOf(order.getDocStatus()))) {
            return new JsonResult<String>().error("只有执行状态的订单才能生成合同");
        }
        
        // 这里可以添加生成合同的逻辑
        // 暂时只更新状态为完结
        order.setDocStatus(80);
        setInsetOrUpdateUser(order);
        purchaseOrderService.updateById(order);
        
        return new JsonResult<String>().success("合同生成成功", null);
    }

    /**
     * 审核通过订单
     */
    @PostMapping("/approve/{id}")
    public JsonResult<String> approveOrder(@PathVariable("id") String id) {
        // 检查用户权限
        if (!hasAuditPermission()) {
            return new JsonResult<String>().error("您没有审核权限");
        }
        
        PurchaseOrder order = purchaseOrderService.getById(id);
        if (order == null) {
            return new JsonResult<String>().error("订单不存在");
        }
        
        // 检查当前状态是否为待审状态
        if (!"30".equals(String.valueOf(order.getDocStatus()))) {
            return new JsonResult<String>().error("只有待审状态的订单才能审核");
        }
        
        // 更新状态为执行
        order.setDocStatus(70);
        setInsetOrUpdateUser(order);
        purchaseOrderService.updateById(order);
        
        return new JsonResult<String>().success("订单审核通过", null);
    }

    /**
     * 审核驳回订单
     */
    @PostMapping("/reject/{id}")
    public JsonResult<String> rejectOrder(@PathVariable("id") String id, @RequestBody RejectRequest request) {
        // 检查用户权限
        if (!hasAuditPermission()) {
            return new JsonResult<String>().error("您没有审核权限");
        }
        
        PurchaseOrder order = purchaseOrderService.getById(id);
        if (order == null) {
            return new JsonResult<String>().error("订单不存在");
        }
        
        // 检查当前状态是否为待审状态
        if (!"30".equals(String.valueOf(order.getDocStatus()))) {
            return new JsonResult<String>().error("只有待审状态的订单才能审核");
        }
        
        // 更新状态为驳回，并保存驳回原因到attr1字段
        order.setDocStatus(11);
        order.setAttr1(request.getRejectReason());
        setInsetOrUpdateUser(order);
        purchaseOrderService.updateById(order);
        
        return new JsonResult<String>().success("订单已驳回", null);
    }

    /**
     * 合同履约完成
     */
    @PostMapping("/fulfill/{id}")
    public JsonResult<String> fulfillOrder(@PathVariable("id") String id) {
        PurchaseOrder order = purchaseOrderService.getById(id);
        if (order == null) {
            return new JsonResult<String>().error("订单不存在");
        }
        
        // 检查当前状态是否为执行状态
        if (!"70".equals(String.valueOf(order.getDocStatus()))) {
            return new JsonResult<String>().error("只有执行状态的订单才能履约");
        }
        
        // 更新状态为完成
        order.setDocStatus(80);
        setInsetOrUpdateUser(order);
        purchaseOrderService.updateById(order);
        
        return new JsonResult<String>().success("合同履约完成", null);
    }

    /**
     * 打回重审（仅限执行状态70的订单）
     */
    @PostMapping("/rejectForRevision/{id}")
    public JsonResult<String> rejectForRevision(@PathVariable("id") String id, @RequestBody RejectRequest request) {
        // 检查用户权限
        if (!hasAuditPermission()) {
            return new JsonResult<String>().error("您没有审核权限");
        }
        
        PurchaseOrder order = purchaseOrderService.getById(id);
        if (order == null) {
            return new JsonResult<String>().error("订单不存在");
        }
        
        // 检查当前状态是否为执行状态
        if (!"70".equals(String.valueOf(order.getDocStatus()))) {
            return new JsonResult<String>().error("只有执行状态的订单才能打回重审");
        }
        
        try {
            // 调用服务层处理打回重审逻辑
            return purchaseOrderService.rejectForRevision(order, request.getRejectReason());
        } catch (Exception e) {
            return new JsonResult<String>().error("打回重审失败：" + e.getMessage());
        }
    }

    /**
     * 查询订单历史版本
     */
    @PostMapping("/getHistoryVersions/{id}")
    public JsonResult<java.util.List<PurchaseOrder>> getHistoryVersions(@PathVariable("id") String id) {
        try {
            return purchaseOrderService.getHistoryVersions(id);
        } catch (Exception e) {
            return new JsonResult<java.util.List<PurchaseOrder>>().error("查询历史版本失败：" + e.getMessage());
        }
    }

    /**
     * 检查用户是否有审核权限
     */
    private boolean hasAuditPermission() {
        try {
            LoginUserInfo user = UserContextUtil.getUser();
            if (user == null) {
                return false;
            }
            // 只有角色为0（超级管理员）和1（管理员）时拥有审核权限
            return user.getRoleType() == 0 || user.getRoleType() == 1;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 驳回请求类
     */
    public static class RejectRequest {
        private String rejectReason;
        
        public String getRejectReason() {
            return rejectReason;
        }
        
        public void setRejectReason(String rejectReason) {
            this.rejectReason = rejectReason;
        }
    }

    /**
     * 根据合同ID获取当前合同订单
     */
    @PostMapping("/getCurrentOrderByContract")
    public JsonResult<List<PurchaseOrder>> getCurrentOrderByContract(@RequestBody Map<String, String> params) {
        try {
            String contractId = params.get("contractId");
            String relatedOrderNo = params.get("relatedOrderNo");
            
            if (relatedOrderNo == null || relatedOrderNo.trim().isEmpty()) {
                return new JsonResult<List<PurchaseOrder>>().error("关联订单号不能为空");
            }
            
            // 根据关联订单号查询订单（使用订单号查询，不是主键）
            QueryWrapper<PurchaseOrder> wrapper = new QueryWrapper<>();
            wrapper.eq("order_no", relatedOrderNo);
            wrapper.eq("is_delete", 0);
            PurchaseOrder order = purchaseOrderService.getOne(wrapper);
            
            if (order == null) {
                return new JsonResult<List<PurchaseOrder>>().error("订单不存在，订单号：" + relatedOrderNo);
            }
            
            // 设置前端需要的字段
            order.setPurchaseOrderId(order.getId());
            
            // 查询供应商名称并设置到订单对象中
            if (order.getSupId() != null) {
                order.setSupName("供应商-" + order.getSupId());
            } else {
                order.setSupName("未知供应商");
            }
            
            // 将单个对象包装成数组，因为前端表格期望数组格式
            List<PurchaseOrder> orderList = new ArrayList<>();
            orderList.add(order);
            
            return new JsonResult<List<PurchaseOrder>>().success(orderList);
        } catch (Exception e) {
            return new JsonResult<List<PurchaseOrder>>().error("查询当前合同订单失败：" + e.getMessage());
        }
    }

    /**
     * 根据合同ID获取历史订单（基于UUID反序列化）
     */
    @PostMapping("/getHistoryOrdersByContract")
    public JsonResult<List<PurchaseOrder>> getHistoryOrdersByContract(@RequestBody Map<String, String> params) {
        try {
            String contractId = params.get("contractId");
            String relatedOrderNo = params.get("relatedOrderNo");
            
            if (relatedOrderNo == null || relatedOrderNo.trim().isEmpty()) {
                return new JsonResult<List<PurchaseOrder>>().error("关联订单号不能为空");
            }
            
            // 先查询当前订单，获取其UUID
            QueryWrapper<PurchaseOrder> currentOrderWrapper = new QueryWrapper<>();
            currentOrderWrapper.eq("order_no", relatedOrderNo);
            currentOrderWrapper.eq("is_delete", 0);
            PurchaseOrder currentOrder = purchaseOrderService.getOne(currentOrderWrapper);
            
            if (currentOrder == null) {
                return new JsonResult<List<PurchaseOrder>>().error("当前订单不存在，订单号：" + relatedOrderNo);
            }
            
            // 使用UUID反序列化查询历史订单
            JsonResult<List<PurchaseOrder>> historyResult = purchaseOrderService.getHistoryVersions(currentOrder.getId());
            
            if (historyResult.getCode() != 0) {
                return new JsonResult<List<PurchaseOrder>>().error("查询历史订单失败：" + historyResult.getMessage());
            }
            
            List<PurchaseOrder> historyOrders = historyResult.getData();
            
            // 为每个订单设置前端需要的字段
            for (PurchaseOrder order : historyOrders) {
                order.setPurchaseOrderId(order.getId());
                // 设置供应商名称
                if (order.getSupId() != null) {
                    order.setSupName("供应商-" + order.getSupId());
                } else {
                    order.setSupName("未知供应商");
                }
            }
            
            return new JsonResult<List<PurchaseOrder>>().success(historyOrders);
        } catch (Exception e) {
            return new JsonResult<List<PurchaseOrder>>().error("查询历史订单失败：" + e.getMessage());
        }
    }
}


